<template>
  <!-- 城市资源标注 -->
  <div class="city-resources-mark-wrap">
    <el-row>
      <el-col :span="5">
        <el-form :model="markInfoForm" :rules="markInfoFormRules" ref="markInfoForm" @submit.native.prevent>
          <el-form-item label="联网单位：" prop='organizationId'>
            <el-select filterable v-model="markInfoForm.organizationId">
              <el-option
                v-for="item in orgList"
                :key="item.organizationId"
                :label="item.shortName"
                :value="item.organizationId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择打点类型：" prop='markType'>
            <el-select v-model="markInfoForm.markType">
              <el-option
                v-for="item in markTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="bindLabelTxt" prop='markObjectId'>
            <el-select filterable v-model="markInfoForm.markObjectId">
              <el-option
                v-for="item in bindList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="具体位置：" prop='position'>
            <el-input v-model="markInfoForm.position"></el-input>
          </el-form-item>
          <el-form-item label="经度：" prop='lon'>
            <el-input type="number" v-model="markInfoForm.lon"></el-input>
          </el-form-item>
          <el-form-item label="纬度：" prop='lat'>
            <el-input type="number" v-model="markInfoForm.lat"></el-input>
          </el-form-item>
          <el-form-item label="经纬度：" prop='lonLat'>
            <el-input v-model="markInfoForm.lonLat"></el-input>
          </el-form-item>
          <el-form-item >
            <el-row type="flex" justify="end">
              <el-button class="form-search-btn" type="primary" @click="clearLonLat">清空</el-button>
              <el-button class="form-search-btn" type="primary" @click="saveMarkInfo('markInfoForm')">保存</el-button>
            </el-row>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18" :offset="1">
        <!-- 地图 -->
        <div>
          <el-row type="flex" justify="start">
            <h3 style="height: 50px;line-height: 50px;margin-right: 20px;">地图</h3>
            <!-- <img v-if="logoUrl!=''" :src="logoUrl" width="40px" height="40px"> -->
          </el-row>
          <bmap-model ref="bMap" v-on:newMarkPoint="newMarkPoint"></bmap-model>
        </div>
        <!-- 列表 -->
        <div>
          <el-row style="margin-bottom: 15px;margin-top: 15px;">
            <h3>标注列表</h3>
          </el-row>
          <el-row>
            <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
              <el-form-item>
                <el-input
                  placeholder="名称"
                  v-model="searchForm.markName"
                  @keyup.enter.native="getTableData"
                  clearable>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="form-search-btn" type="primary" @click="getTableData">查询</el-button>
              </el-form-item>
            </el-form>
          </el-row>
          <el-table
            v-loading="loading"
            ref="markTableList"
            :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
            style="width: 100%">
            <el-table-column label="序号" type="index" width="50"></el-table-column>
            <el-table-column label="名称" prop="markName"></el-table-column>
            <el-table-column label="经度" prop="lon"></el-table-column>
            <el-table-column label="纬度" prop="lat"></el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button @click="showPoint(scope.row.lon, scope.row.lat)" type="text" size="small">定位</el-button>
                <span class="dividing-line">|</span>
                <el-button @click="deleteMark(scope.row)" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            @current-change="currentChange">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import bmapModel from './Pagemodel/BMap'
  import { getOrgList } from '@/api/org'
  import util from '@/utils/util'
  import { getMapsMarkersByType, getListForMap, getMarkRelatFcfInfo, saveMapMarkExt, delMapsMakers } from '@/api/sysConfig'

  export default {
    name: 'CityResourceMark',
    components: {
      bmapModel
    },
    data() {
      return {
        loading: false,
        orgList: [],
        markTypeList: [], // 打点类型选项
        bindLabelTxt: '关联联网单位', // 关联信息label文案
        bindList: [], // 关联信息数据
        markInfoForm: {
          id: '',
          organizationId: '',
          markType: 11,
          markObjectId: '', // 关联业主单位
          lon: '',
          lat: '',
          position: '',
          lonLat: ''
        },
        markInfoFormRules: {
          markObjectId: [
            { required: true, message: '请选择'+this.bindLabelTxt, trigger: 'blur' }
          ],
          lon: [
            { required: true, message: '请输入经度', trigger: 'change' }
          ],
          lat: [
            { required: true, message: '请输入纬度', trigger: 'change' }
          ]
        },
        searchForm: {
          markName: ''
        },
        logoUrl: '', // logo图片
        tableData: [], // 地图标注列表信息
        total: 0,
        pagesize: 10,
        currentPage: 1
      }
    },
    created() {
      let that = this
      // 获取业主单位信息
      getOrgList({
        queryType: 0
      }).then(res => {
        if(res.status = 200) {
          that.orgList = res.data
          // 初始选中第一个单位
          that.markInfoForm.organizationId = res.data[0].organizationId
          // 获取地图标注点信息
          that.getMapMarkInfo()
          // 加载列表
          that.getTableData()
        }
      })
      // 获取打点类型
      util.ilinkArrHandle.delDicArr_keyVal(71, (arr) => {
        that.markTypeList.push.apply(that.markTypeList, arr)
        if(arr!=null && arr.length>0){
          this.bindLabelTxt = "关联"+arr[0].name+":"
        }
      })
    },
    methods: {
      // 获取关联数据
      getBindData() {
        let that = this
        getMarkRelatFcfInfo({
          orgId: that.markInfoForm.organizationId,
          type: that.markInfoForm.markType
        }).then(res => {
          if(res.status === 200) {
            that.bindList = res.data
            // 默认选择第一个
            if( res.data!=null &&  res.data.length>0){
              that.markInfoForm.markObjectId = res.data[0].id
            }else{
              that.markInfoForm.markObjectId = ''
            }
          }
        })
      },
      // 百度地图初始化
      bMapInit() {
        let that = this

        that.$refs['bMap'].clearMarkPoint()
        that.$refs['bMap'].initMap()
        that.getMapMarkInfo()
      },
      // 获取地图打点信息
      getMapMarkInfo() {
        let that = this
        getListForMap({organizationIds: that.markInfoForm.organizationId}).then(res => {
          if(res.status === 200) {
            // 显示logo
            that.logoUrl = res.data[0].logoUrl
            // 调用地图组件中的打点方法
            that.$refs['bMap'].addMarker(res.data[0].longitude, res.data[0].latitude)
          }
        })
      },
      // 清空经纬度
      clearLonLat() {
        let that = this
        that.markInfoForm.lon = ''
        that.markInfoForm.lat = ''
        that.markInfoForm.position = ''
      },
      // 保存
      saveMarkInfo(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        let parames = {}

        // 校验表单
        that.$refs[formName].validate((valid) => {
          if(valid) {
            parames = {
              id: 0,
              organizationId: that.markInfoForm.organizationId,
              markType: that.markInfoForm.markType,
              markObjectId: that.markInfoForm.markObjectId,
              lon: that.markInfoForm.lon,
              lat: that.markInfoForm.lat,
              markName:  this.markTypeList.find(item =>{return item.id === that.markInfoForm.markType}).name,
              lonLat: that.markInfoForm.lonLat
            }
            saveMapMarkExt(parames).then(res => {
              if(res.status === 200) {
                if(res.data == 0) {
                  that.$message({
                    message: '保存成功！',
                    type: 'success'
                  })
                } else {
                  that.$message({
                    message: '标注重复！',
                    type: 'warning'
                  })
                }

                // 清除经纬度
                that.clearLonLat()
                that.$refs['bMap'].saveSuccess()
                that.bMapInit()
                // 刷新列表
                that.getTableData()
              } else {
                that.$message({
                  message: '保存失败！',
                  type: 'warning'
                })
              }
            })
          } else {
            return false
          }
        })
      },
      // 获取地图标注列表信息
      getTableData() {
        let that =this
        let parames = {
          orgIds: that.markInfoForm.organizationId,
          markTypes: that.markInfoForm.markType,
          markName: that.searchForm.markName.trim(),
          order: 'desc',
          offset: 0,
          limit: 10
        }

        getMapsMarkersByType(parames).then(res => {
          if(res.status === 200) {
            that.tableData = res.data
            that.total = res.total
            // 调用地图组件中的清楚标记点方法
            that.$refs['bMap'].clearMarkPoint()
            // 调用地图组件中的设置地图标注点信息方法
            that.$refs['bMap'].setMapMarkInfo(that.markInfoForm.markType, res.data)
          }
        })
      },
      // 获取经纬度
      newMarkPoint(lon, lat, addr) {
        let that = this
        that.markInfoForm.lon = lon
        that.markInfoForm.lat = lat
        that.markInfoForm.position = addr
      },
      currentChange(currentPage) {
        this.currentPage = currentPage;
      },
      // 定位
      showPoint(lon, lat) {
        var that = this
        // 调用地图组件中的定位方法
        that.$refs['bMap'].showPoint(lon, lat)
      },
      // 删除
      deleteMark(row) {
        let that = this
        if (row) {
          that.$confirm('确定要删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            roundButton: true
          }).then(() => {
            // 调用删除接口
            delMapsMakers({
              id: row.id
            }).then(res => {
              if( res.status === 200) {
                that.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                that.bMapInit()
                // 刷新列表
                that.getTableData()
              }else{
                that.$message.error(res.info)
              }
            })
          }).catch(() => {
          })
        }
      },
      // 映射关联字段label名称
      mapBindLabel(id) {
        let that = this
        let list = that.markTypeList

        for(var i=0, len=list.length; i < len; i++) {
          if(id == list[i].id) {
            that.bindLabelTxt = '关联' + list[i].name + '：'
            break
          }
        }
      }
    },
    watch: {
      // 监听业主单位值变化
      orgIdSelect(val, oldVal) {
        if(val !== oldVal) {
          // 重新获取关联
          this.getBindData()
          // 重新获取列表
          this.getTableData()
        }
      },
      // 监听打点类型变化
      markTypeSelect(val, oldVal) {
        if(val !== oldVal) {
          // 映射关联字段label名称
          this.mapBindLabel(val)
          // 重新获取关联
          this.getBindData()
          // 重新获取列表
          this.getTableData()
        }
      },
    },
    computed: {
      orgIdSelect() {
        return this.markInfoForm.organizationId
      },
      markTypeSelect() {
        return this.markInfoForm.markType
      },
    },
  }
</script>
